#! /usr/bin/bash
# -*- coding: utf-8 -*-

import os
import sys
import time
import pickle
import snap7
import struct
from kafka import *

import threading

import app_global

log = app_global.gLog

class CDataSetter(threading.Thread):
    def __init__(self,conf=None):
        threading.Thread.__init__(self)
        #create kafka consumer
        self.kfk_c = KafkaConsumer(bootstrap_servers=['0.0.0.0:9092'],auto_offset_reset='latest')
        self.kfk_c.subscribe(['data_set'])
        #create snap7 client
        self.s7_clt = snap7.client.Client()
        self.s7_clt.connect("192.100.1.45",0,3)
       

    def run(self):
        while app_global.SYS_RUN:
            if self.kfk_c:
                try:
                    self.kfk_c.poll(timeout_ms=5)
                    for msg in self.kfk_c:
                        key = msg.key.decode(encoding="utf-8")               #因为接收到的数据时bytes类型，因此需要解码
                        value = pickle.loads(msg.value)

                        log.info("recv msg: \n{}\n{}".format(key,value))

                        if key=="set_data":
                            if isinstance(value,list):
                                for it in value:
                                    self.plc_write(it["db"],it["stx"],it["value"])
                            elif isinstance(value,dict):
                                self.plc_write(value["db"],value["stx"],value["value"])

                except Exception as e:
                    log.error("err: {}".format(e))

            time.sleep(1)

    def get_packmask(self, val):
        str_mask=None
        if isinstance(var,int):
            str_mask= ">i"
        elif isinstance(var,float):
            str_mask= ">f"
        return str_mask

    def plc_write(db,stx,val):
        if self.s7_clt:
            try:
                str_maks = self.get_packmask(val)
                if str_maks:
                    self.s7_clt.db_write(db,stx,bytearray(pack(str_mask,val)))
            except Exception as e:
                log.error("write s7 plc err:{}".format( e))
